package com.framework.controller.system;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.framework.annotation.SystemLog;
import com.framework.controller.index.BaseController;
import com.framework.entity.ConsoleuserFormMap;
import com.framework.entity.DatacenterFormMap;
import com.framework.entity.DatasourceFormMap;
import com.framework.entity.DatasourceFuncFormMap;
import com.framework.entity.HewkeuserFormMap;
import com.framework.entity.ResFormMap;
import com.framework.entity.ResUserFormMap;
import com.framework.entity.UserRoleFormMap;
import com.framework.entity.factory.FormmapFactory;
import com.framework.entity.ClientDatasourceFormMap;
import com.framework.entity.view.DatasourceFuncAllViewFormMap;
import com.framework.entity.view.DatasourceFuncViewFormMap;
import com.framework.entity.view.UsersourceViewFormMap;
import com.framework.exception.ParameterException;
import com.framework.plugin.PageView;
import com.framework.plugin.test.ContextHolder;
import com.framework.plugin.token.Token;
import com.framework.util.Common;
import com.framework.util.GetDataFromOtherDB;
import com.framework.util.PasswordHelper;
import com.framework.util.TreeObject;
import com.framework.util.TreeUtil;

@Controller
@RequestMapping("/datacenter/")
public class DatacenterController extends BaseController {
	List<ResFormMap> res = null;
	public static StringBuffer sb;

	// 获取界面UI
	@RequestMapping(value = "list")
	public String listUI(Model model) throws Exception {
		res = findByRes();
		model.addAttribute("res", getButtomM(res));
		return Common.BACKGROUND_PATH + "/system/datacenter/list";
	}

	@ResponseBody
	@RequestMapping("findByPage")
	@SystemLog(module = "系统基础管理", methods = "数据中心-查询") // 凡需要处理业务逻辑的.都需要记录操作日志
	@Transactional(readOnly = false) // 需要事务操作必须加入此注解
	public PageView findByPage(String draw, String length, String start) throws Exception {
		DatasourceFuncViewFormMap datasourceFuncViewFormMap=new DatasourceFuncViewFormMap();
		datasourceFuncViewFormMap.put("name", "CRM");
		datasourceFuncViewFormMap.put("$orderby", getorder());
		datasourceFuncViewFormMap.put("$search", getsearch());
		datasourceFuncViewFormMap.put("keyCloumn",  getKeyCloumn());
		datasourceFuncViewFormMap = toFormMap(datasourceFuncViewFormMap, draw, length, start);
		pageView=datasourceFuncViewFormMap.findByPage_Names(pageView);
		return pageView;
	}

	@ResponseBody
	@RequestMapping("findByPage2")
	public PageView findByPage2(String draw, String length, String start) throws Exception {
		DatasourceFuncAllViewFormMap formMap = new DatasourceFuncAllViewFormMap();
		formMap.put("$orderby", getorder());
		formMap.put("$search", getsearch());
		formMap.put("keyCloumn", "owner,db_name,manager");
		formMap = toFormMap(formMap, draw, length, start);
		pageView.setData(formMap.findByNames());
		return pageView;
	}

	@ResponseBody
	@RequestMapping("getButton")
	public String getButton() throws Exception {
		return getButtomB(res);
	}

	/**
	 * 仅限总控制台使用
	 * 
	 * @author 李品良
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("addEnUser")
	@SystemLog(module = "系统基础管理", methods = "数据中心-新增企业用户") // 凡需要处理业务逻辑的.都需要记录操作日志
	@Transactional(readOnly = false) // 需要事务操作必须加入此注解
	public String addEnUser(Model model) throws Exception {

		DatacenterFormMap datacenterFormMap = getFormMap(DatacenterFormMap.class);

		String fathercellphone = datacenterFormMap.get("fathercellphone").toString();
		// 说明是我的总控制台发起的注册申请
		String cellphone = datacenterFormMap.get("cellphone").toString();
		if (!Common.isNumeric(cellphone)) {
			return "failed";
		}
		String username = datacenterFormMap.get("username").toString();
		String password = datacenterFormMap.get("password").toString();
		PasswordHelper passwordHelper = new PasswordHelper();
		String salt = passwordHelper.getSalt();
		String newPassword = passwordHelper.encryptPassword(cellphone, password, salt);
		datacenterFormMap.put("password", newPassword);
		ConsoleuserFormMap hewkeuserFormMap = new ConsoleuserFormMap();
		hewkeuserFormMap.put("parentId", datacenterFormMap.get("parentId").toString());
		hewkeuserFormMap.put("userName", username);
		hewkeuserFormMap.put("accountName", cellphone);
		hewkeuserFormMap.put("password", newPassword);
		hewkeuserFormMap.put("credentialsSalt", salt);
		hewkeuserFormMap.put("tel", cellphone);
		// 连接用户数据库
		UsersourceViewFormMap usersourceViewFormMap = new UsersourceViewFormMap();
		usersourceViewFormMap.put("cellphone", fathercellphone);
		usersourceViewFormMap = usersourceViewFormMap.findbyFrist();

		GetDataFromOtherDB.switchDataSource(usersourceViewFormMap);
		if (!ContextHolder.getCustomerType().equals(fathercellphone)) {
			return "failed";
		}
		hewkeuserFormMap.save();

		// 不应该切换来切换去啊
		// 切换回来
		ContextHolder.setCustomerType(ContextHolder.DATA_SOURCE_A);
		datacenterFormMap.put("level", Integer.parseInt(datacenterFormMap.get("level").toString()) + 1);
		datacenterFormMap.put("nickname", username);
		datacenterFormMap = datacenterFormMap.save();
		// 保存关系
		saveRelationship(datacenterFormMap, usersourceViewFormMap);

		// 更新套餐-----用户数量
		String client_id = usersourceViewFormMap.getStr("client_id");
		String datasource_id = usersourceViewFormMap.getStr("datasource_id");
		// HashMap<String, Object> hashMap=new HashMap<>();
		// hashMap.put("", value);
		// updateDateValue(count, hashMap);
		return "success";
	}

	/**
	 * 保存关系
	 * 
	 * @author 李品良
	 * @param datacenterFormMap
	 *            存在的用户对象
	 * @param usersourceViewFormMap
	 */
	private void saveRelationship(DatacenterFormMap datacenterFormMap, UsersourceViewFormMap usersourceViewFormMap) {
		ClientDatasourceFormMap ClientDatasourceFormMap = new ClientDatasourceFormMap();
		ClientDatasourceFormMap.put("client_id", datacenterFormMap.get("id"));
		ClientDatasourceFormMap.put("datasource_id", usersourceViewFormMap.get("datasource_id"));
		ClientDatasourceFormMap.put("status", 1);
		try {
			ClientDatasourceFormMap.save();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 显示修改活动页面
	@RequestMapping("competenceUI")
	@Token(save = true)
	public String competenceUI(Model model) {
		String id = getPara("id");
		if (Common.isNotEmpty(id)) {
			model.addAttribute("datauserFormMap", new DatacenterFormMap().findById(id));
		}
		return Common.BACKGROUND_PATH + "/system/resources/permissions";
	}

	// 显示修改空间套餐
	@RequestMapping("editSpaceUI")
	@Token(save = true)
	public String editSpaceUI(Model model) {
		DatasourceFuncViewFormMap formMap = getMapformDataMap(DatasourceFuncViewFormMap.class,
				getMapFromRequest());
		formMap.put("name", "空间套餐");
		formMap = formMap.findbyFrist();
		if (formMap != null) {
			model.addAttribute("formMap", formMap);
			// 查出空间套餐
			DatafunctionFormMap datafunctionFormMap = new DatafunctionFormMap();
			datafunctionFormMap.put("name", "空间套餐");
			datafunctionFormMap = datafunctionFormMap.findbyFrist();

			datafunctionFormMap.put("where",
					"parentId=30");
			List<DatafunctionFormMap> list = datafunctionFormMap.findByWhere();

			datafunctionFormMap.put("childLists", list);

			model.addAttribute("datafunctionFormMap", datafunctionFormMap);
			return Common.BACKGROUND_PATH + "/system/datacenter/editSpaceUI";
		}
		return Common.BACKGROUND_PATH + "/system/404/404";
	}

	// 显示修改活动页面
	@RequestMapping("editEnUI")
	@Token(save = true)
	public String editEnUI(Model model) {
		DatasourceFuncViewFormMap formMap = getMapformDataMap(DatasourceFuncViewFormMap.class,
				getMapFromRequest());
		formMap.put("name", "CRM");
		formMap = formMap.findbyFrist();
		if (formMap != null) {
			model.addAttribute("formMap", formMap);
			// 查出空间套餐
			DatafunctionFormMap datafunctionFormMap = new DatafunctionFormMap();
			datafunctionFormMap.put("name", "CRM");
			datafunctionFormMap = datafunctionFormMap.findbyFrist();

			datafunctionFormMap.put("where",
					"parentId=10");
			List<DatafunctionFormMap> list = datafunctionFormMap.findByWhere();

			datafunctionFormMap.put("childLists", list);

			model.addAttribute("datafunctionFormMap", datafunctionFormMap);
			return Common.BACKGROUND_PATH + "/system/datacenter/editSpaceUI";
		}
		return Common.BACKGROUND_PATH + "/system/404/404";
	}

	/**
	 * 要企业人数套餐，
	 * 再找出，我们公司提供的人数套餐列表
	 *	@author 李品良
	 *创建时间：2016年9月24日 下午2:27:35
	 * @param model
	 * @return
	 */
	@RequestMapping("editEntityUI")
	@Token(save = true)
	public String editEntityUI(Model model) {
		DatasourceFuncViewFormMap formMap = getMapformDataMap(DatasourceFuncViewFormMap.class,
				getMapFromRequest());
		formMap.put("name", "人数套餐");
		formMap = formMap.findbyFrist();//1
		if (formMap != null) {
			model.addAttribute("formMap", formMap);
			// 查出空间套餐
			DatafunctionFormMap datafunctionFormMap = new DatafunctionFormMap();
			datafunctionFormMap.put("name", "人数套餐");
			datafunctionFormMap = datafunctionFormMap.findbyFrist();
			if (datafunctionFormMap==null) {
				return Common.BACKGROUND_PATH + "/system/404/404";
			}
			
			datafunctionFormMap.put("where","parentId=20");
			List<DatafunctionFormMap> list = datafunctionFormMap.findByWhere();

			datafunctionFormMap.put("childLists", list);

			model.addAttribute("datafunctionFormMap", datafunctionFormMap);
			return Common.BACKGROUND_PATH + "/system/datacenter/editEntityUI";
		}
		return Common.BACKGROUND_PATH + "/system/404/404";
	}

	@ResponseBody
	@RequestMapping("addUserRes")
	@Token(remove = true)
	@Transactional(readOnly = false) // 需要事务操作必须加入此注解
	@SystemLog(module = "系统管理", methods = "用户管理/组管理-修改权限") // 凡需要处理业务逻辑的.都需要记录操作日志
	public String addUserRes(Model model, HttpServletRequest httpServletRequest) throws Exception {
		String u = getPara("userId");
		String g = getPara("roleId");
		String id = "";
		ConsoleuserFormMap hewkeuserFormMap;

		if (u.equals("")) {
			Subject subject = SecurityUtils.getSubject();
			Session session = subject.getSession();
			UsersourceViewFormMap usersourceViewFormMap = (UsersourceViewFormMap) session
					.getAttribute("usersourceViewFormMap");
			GetDataFromOtherDB.switchDataSource(usersourceViewFormMap);
			id = session.getAttribute("id").toString();
		}
		if (null != u && !Common.isEmpty(u.toString())) {
			id = u.toString();
		} else if (null != g && !Common.isEmpty(g.toString())) {
			List<UserRoleFormMap> gs = new UserRoleFormMap().findByAttribute("roleId", g.toString());
			for (UserRoleFormMap ug : gs) {
				id += ug.get("userId") + ",";
			}
		}
		id = Common.trimComma(id);
		String[] users = id.split(",");

		if (ContextHolder.getCustomerType().equals("dataSource")) {
			return "failed";
		}

		ResUserFormMap resUserFormMap = new ResUserFormMap();
		for (String uid : users) {
			resUserFormMap.deleteByAttribute("userId", uid);
			String[] s = getParaValues("resId[]");
			List<ResUserFormMap> resUserFormMaps = new ArrayList<ResUserFormMap>();
			for (String rid : s) {
				resUserFormMap = new ResUserFormMap();
				resUserFormMap.put("resId", rid);
				resUserFormMap.put("userId", id);
				resUserFormMaps.add(resUserFormMap);
			}
			resUserFormMap.batchSave(resUserFormMaps);
		}
		ContextHolder.setCustomerType(ContextHolder.DATA_SOURCE_A);

		return "success";
	}

	@ResponseBody
	@RequestMapping("findRes")
	public List<ResFormMap> findUserRes(Model model, HttpServletRequest httpServletRequest,
			HttpServletResponse response) throws Exception {
		Subject subject = SecurityUtils.getSubject();
		Session session = subject.getSession();
		List<ResFormMap> rs = (List<ResFormMap>) session.getAttribute("rs");
		return rs;
	}

	@ResponseBody
	@RequestMapping("addFuncPackage")
	public String addFuncPackage(Model model, HttpServletRequest httpServletRequest, HttpServletResponse response)
			throws Exception {
		HashMap<String, Object> hashMap = getMapFromRequest();
		DatasourceFormMap datasourceFormMap = getMapformDataMap(DatasourceFormMap.class, hashMap);

		return "failed";
	}

	/**
	 * 权限分配页面
	 * 
	 * @author framework Email：g5874589652@126.com date：2015-4-14
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("permissions")
	@Token(save = true)
	public String permissions(Model model, HttpServletRequest httpServletRequest) throws Exception {

		HashMap<String, Object> hashMap = getMapFromRequest();
		ResFormMap resFormMap = getFormMap(ResFormMap.class);
		HewkeuserFormMap consoleuserFormMap = getFormMap(HewkeuserFormMap.class);

		List<ResFormMap> rs = null;
		//
		Subject subject = SecurityUtils.getSubject();
		Session session = subject.getSession();

		// 这里要切换数据库了，根据名字到tc_user表中查询，
		UsersourceViewFormMap usersourceViewFormMap = FormmapFactory.getBeanFormMap(UsersourceViewFormMap.class);
		usersourceViewFormMap = getMapformDataMap(UsersourceViewFormMap.class, hashMap);
		usersourceViewFormMap.remove("id");
		usersourceViewFormMap = usersourceViewFormMap.findbyFrist();
		try {
			GetDataFromOtherDB.switchDataSource(usersourceViewFormMap);
			///////////////////
			List<ResFormMap> mps = resFormMap.findByWhere();
			List<TreeObject> list = new ArrayList<TreeObject>();
			for (ResFormMap map : mps) {
				TreeObject ts = new TreeObject();
				Common.flushObject(ts, map);
				list.add(ts);
			}
			TreeUtil treeUtil = new TreeUtil();
			List<TreeObject> ns = treeUtil.getChildTreeObjects(list, 0);
			model.addAttribute("permissions", ns);
			// 开始查询

			consoleuserFormMap.put("accountName", usersourceViewFormMap.get("cellphone"));

			consoleuserFormMap = consoleuserFormMap.findbyFrist();
		} catch (Exception e) {
			ContextHolder.setCustomerType(ContextHolder.DATA_SOURCE_A);
			getLogger(this.getClass()).error(e);
			return Common.BACKGROUND_PATH + "/system/404/404";
		}
		if (consoleuserFormMap == null) {
			ContextHolder.setCustomerType(ContextHolder.DATA_SOURCE_A);
			return Common.BACKGROUND_PATH + "/system/404/404";
		}
		String userDBId = consoleuserFormMap.get("id").toString();
		resFormMap.put("id", userDBId);
		// 这个id才是最后的id
		resFormMap.remove("userId");

		rs = ResFormMap.mapper().findUserResourcess(userDBId);

		session.setAttribute("id", userDBId);
		session.setAttribute("hewkeuserFormMap", consoleuserFormMap);
		// 保存id
		session.setAttribute("usersourceViewFormMap", usersourceViewFormMap);
		session.setAttribute("rs", rs);
		//
		ContextHolder.setCustomerType(ContextHolder.DATA_SOURCE_A);
		/////////////////////////
		return Common.BACKGROUND_PATH + "/system/datacenter/permissions";
	}

	// 获取界面UI
	/**
	 * 先找父亲，得到相关的信息，
	 * 
	 * @author 李品良
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "addEnUserUI")
	public String addEnUserUI(Model model) throws Exception {
		String id = getPara("id");
		if (Common.isNotEmpty(id)) {
			DatacenterFormMap datacenterFormMap = getFormMap(DatacenterFormMap.class);
			datacenterFormMap.put("id", id);
			datacenterFormMap = datacenterFormMap.findbyFrist();
			String level = datacenterFormMap.get("level").toString();
			if (datacenterFormMap.containsKey("level")) {
				model.addAttribute("datacenterFormMap", datacenterFormMap);
				return Common.BACKGROUND_PATH + "/system/datacenter/addEnUser";
			}
		}
		model.addAttribute("id", id);
		return Common.BACKGROUND_PATH + "/system/404/404";
	}

	// 获取界面UI
	@RequestMapping(value = "clientInfoUI")
	public String clientInfoUI(Model model) throws Exception {
		HashMap<String, Object> hashMap = getMapFromRequest();
		DatasourceFuncViewFormMap datasourceFuncViewFormMap = getMapformDataMap(
				DatasourceFuncViewFormMap.class, hashMap);
		// 记住，我要db_name
		if (datasourceFuncViewFormMap.containsKey("db_name")) {
			if (datasourceFuncViewFormMap != null && datasourceFuncViewFormMap.containsKey("owner")) {
				// 那么就是真正的老爸
				// 更新空间值
				String db_name = datasourceFuncViewFormMap.getStr("db_name");
				// String result=refreshClinetSpace(db_name, client_id);
				// if (result.equals("failed")) {
				// return Common.BACKGROUND_PATH + "/system/404/404";
				// }
				//
				model.addAttribute("db_name", db_name);
				List<DatasourceFuncViewFormMap> list=datasourceFuncViewFormMap.findByNames();
				
				if (list.size()!=3) {
					return Common.BACKGROUND_PATH + "/system/404/404";
				}
				
				model.addAttribute("func_crm", list.get(0));
				model.addAttribute("func_entity", list.get(1));
				model.addAttribute("func_space", list.get(2));
				return Common.BACKGROUND_PATH + "/system/datacenter/clientInfo";
			} else {
				return Common.BACKGROUND_PATH + "/system/404/404";
			}
		}
		return Common.BACKGROUND_PATH + "/system/404/404";
	}

	/**
	 * 查找企业所有用户
	 * 
	 * @author 李品良
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "searchEnUserList")
	public List<DatacenterFormMap> searchEnUserList(Model model) throws Exception {
		HashMap<String, Object> hashMap = getMapFromRequest();
		hashMap.remove("id");
		UsersourceViewFormMap usersourceViewFormMap = getMapformDataMap(UsersourceViewFormMap.class, hashMap);
		if (hashMap != null) {

			usersourceViewFormMap.put("where", "level>0 and db_name='" + usersourceViewFormMap.getStr("db_name") + "'");

			List<DatacenterFormMap> list = usersourceViewFormMap.findByWhere();
			return list;
		}
		return null;
	}

	public boolean isLockStatus(Map<String, Object> map) {
		String lockStatus = map.get("lock_status").toString();
		if (lockStatus.equals("0")) {
			return true;
		}
		return false;
	}

	// 新增企业用户接口
	/**
	 * 父亲的电话，接下来就是DatacenterFormMap，实体类，用来保存的信息 仅限管理系统使用
	 * 
	 * @author 李品良 ,fatherCellphone,tel,username
	 * @param model
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("addEnUserInf")
	@SystemLog(module = "系统基础管理", methods = "数据中心-新增企业用户") // 凡需要处理业务逻辑的.都需要记录操作日志
	@Transactional(readOnly = false) // 需要事务操作必须加入此注解
	public String addEnUserInf(Model model, HttpServletRequest request) throws Exception {

		HashMap<String, Object> hashMap = getMapFromRequest();

		DatacenterFormMap datacenterFormMap = getMapformDataMap(DatacenterFormMap.class, hashMap);

		if (!hashMap.containsKey("fatherCellphone")) {
			return "failed";
		}
		// String username = datacenterFormMap.get("username").toString();
		// String password = datacenterFormMap.get("password").toString();
		String fatherCellphone = hashMap.get("fatherCellphone").toString();
		DatacenterFormMap father = new DatacenterFormMap();
		father.put("cellphone", fatherCellphone);

		if (fatherCellphone == null || fatherCellphone.trim().equals("")) {
			return "fatherCellphone failed";
		}
		father = father.findbyFrist();
		Map<String, Object> fatherMap = datacenterFormMap.mapper().findClientInfoViaId(father);
		if (!isLockStatus(fatherMap)) {
			return "isLockStatus failed";
		}
		if (!(hashMap == null || hashMap.size() > 1)) {
			return "datacenterFormMap failed";
		}

		// PasswordHelper passwordHelper = new PasswordHelper();
		// String salt = passwordHelper.getSalt();
		// String newPassword = passwordHelper.encryptPassword(username,
		// password, salt);

		hashMap.put("cellphone", hashMap.get("tel"));
		dataFatherToSon(fatherMap, datacenterFormMap);

		String db_name = father.get("db_name").toString();
		int count = getDataSize(db_name);

		boolean isLock = strictNumbers(fatherMap, count);
		if (isLock) {
			return "isLock failed";
		}

		return "success";
	}

	/**
	 * 更新空间，计费实效值
	 * 
	 * @author 李品良
	 * @param count
	 * @param map
	 * @return
	 * @throws Exception
	 */
	public String refreshClinetSpace(String db_name, String client_id) throws Exception {
		DatasourceFormMap datasourceFormMap = new DatasourceFormMap();
		datasourceFormMap.put("db_name", db_name);
		datasourceFormMap = datasourceFormMap.findbyFrist();
		if (datasourceFormMap != null) {
			DatasourceFormMap datasourceFormMap2 = DatasourceFormMap.mapper().findEnSpaceState(datasourceFormMap);
			if (datasourceFormMap != null) {
				String db_used = datasourceFormMap2.getStr("data");
				db_used = db_used.replace("MB", "");
				// 更新datasourceFormMap
				datasourceFormMap.put("enterprise_space", db_used);
				datasourceFormMap.update();
				return "success";
			}
		}
		return "failed";
	}

	/**
	 * 得到 更新人数
	 * 
	 * @author 李品良 创建时间：2016年9月10日 上午11:42:37
	 * @param db_name
	 * @return
	 * @throws Exception
	 */
	public String refreshEnSize(String db_name) throws Exception {
		int count = getDataSize(db_name);
		DatasourceFormMap datasourceFormMap = new DatasourceFormMap();
		datasourceFormMap.put("db_name", db_name);
		datasourceFormMap = datasourceFormMap.findbyFrist();
		datasourceFormMap.put("enterprise_entity", count);
		datasourceFormMap.update();
		return "success";
	}

	public int getDataSize(String db_name) {
		UsersourceViewFormMap usersourceViewFormMap = new UsersourceViewFormMap();
		usersourceViewFormMap.put("db_name", db_name);
		int count = usersourceViewFormMap.findByNames().size();
		return count;
	}

	/**
	 * 转换保存
	 * 
	 * @author 李品良
	 * @param father
	 *            map
	 * @param datacenterFormMap
	 * @throws Exception
	 */
	private void dataFatherToSon(Map<String, Object> father, DatacenterFormMap datacenterFormMap) throws Exception {
		datacenterFormMap.put("parentId", father.get("id"));
		datacenterFormMap.put("level", Integer.parseInt(father.get("level").toString()) + 1);
		datacenterFormMap.put("db_position", father.get("db_position"));
		datacenterFormMap.put("db_name", father.get("db_name"));
		datacenterFormMap.put("db_username", father.get("db_username"));
		datacenterFormMap.put("db_password", father.get("db_password"));
		datacenterFormMap.save();
	}

	private boolean strictNumbers(Map<String, Object> map, int count) throws Exception {
		if (!map.containsKey("funcStrict")) {
			return false;
		}
		int total = Integer.parseInt(map.get("funcStrict").toString());
		if (count >= total) {
			return true;
		}
		return false;
	}

	/**
	 * 判断是不是企业用户
	 * 
	 * @author 李品良
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "isEnUser")
	public String isEnUser(Model model) throws Exception {
		// TODO
		String id = getPara("id");
		// String parentId = getPara("parentId");
		// String name = getPara("name");
		if (Common.isNotEmpty(id)) {
			// 找到这个用户买了什么产品，不分开找，我一次性找
			DatacenterFormMap datacenterFormMap = getFormMap(DatacenterFormMap.class);
			datacenterFormMap.put("id", id);

			Map<String, Object> map = datacenterFormMap.mapper().findClientInfoViaId(datacenterFormMap);

			if (map == null) {
				return "failed";
			}

			String db_name = map.get("db_name").toString();
			if (map.get("parentId").toString().equals("0")) {
				// 说明是老爸，就不找了
			} else {
				// 说明不是老爸，继续找
				datacenterFormMap.clear();
				datacenterFormMap.put("db_name", db_name);
				datacenterFormMap.put("parentId", 0);
				map = datacenterFormMap.mapper().findClientInfoViaId(datacenterFormMap);
			}

			if (map.get("st_id_user") == null) {
				return "failed";
			}
			if (isLockStatus(map)) {
				return "success";
			}
		}
		return "failed";
	}

	/**
	 * 根据用户名--》email，和手机号码来锁住用户
	 * 
	 * @author 李品良
	 * @param accountName
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "lockEnUser")
	public String lockEnUser(String accountName) {
		if (accountName == null) {
			return "failed";
		}

		DatacenterFormMap datacenterFormMap = new DatacenterFormMap();
		if (accountName.contains("@")) {
			datacenterFormMap.put("email", accountName);
		} else {
			datacenterFormMap.put("cellphone", accountName);
		}
		datacenterFormMap = datacenterFormMap.findbyFrist();

		datacenterFormMap.put("status", 2);
		try {
			datacenterFormMap.update();
		} catch (ParameterException e) {
			e.printStackTrace();
			return "参数错误，class com.framework.entity.DatacenterFormMap没有找到id的值！";
		} catch (Exception e) {
			e.printStackTrace();
			return "failed";
		}
		return "success";
	}


	// 显示添加内容的页面
	@RequestMapping("addUI")
	public String addUI(Model model) throws Exception {
		return Common.BACKGROUND_PATH + "/system/datacenter/add";
	}

	// 添加活动详细内容
	@ResponseBody
	@RequestMapping("addEntity")
	@SystemLog(module = "系统管理", methods = "城市管理-新增城市") // 凡需要处理业务逻辑的.都需要记录操作日志
	@Transactional(readOnly = false) // 需要事务操作必须加入此注解
	public String addEntity(Model model) throws Exception {
		DatacenterFormMap datacenterJoinDbFromMap = getFormMap(DatacenterFormMap.class);
		// 插入一条新活动信息
		datacenterJoinDbFromMap.save();
		// TODO 利用username 创建数据库
		// datacenterJoinDbFromMap.mapper().createUserDb(datacenterJoinDbFromMap);
		//
		// datacenterJoinDbFromMap.mapper().useDb(datacenterJoinDbFromMap);
		//
		// datacenterJoinDbFromMap.mapper().restoryDb(datacenterJoinDbFromMap);

		return "success";
	}

	// 删除活动数据
	@ResponseBody
	@RequestMapping("deleteEntity")
	@SystemLog(module = "系统管理", methods = "城市管理-删除城市") // 凡需要处理业务逻辑的.都需要记录操作日志
	@Transactional(readOnly = false) // 需要事务操作必须加入此注解
	public String deleteEntity() throws Exception {
		DatacenterFormMap formMap = new DatacenterFormMap();
		String[] ids = getParaValues("ids");
		if (ids.length > 0) {
			for (int i = 0; i < ids.length; i++) {
				formMap.deleteById(ids[i]);
				// ActdropdownFormMap downFormMap = new ActdropdownFormMap();
				// downFormMap.put("cityid", ids[i]);
				// // 删除活动的同时去删除对应下拉框的数据
				// downFormMap.deleteByNames();
			}
		}
		return "success";
	}

	// 正常思维是无法实现的
	@RequestMapping("editUI")
	public String editUI(Model model) {
		String id = getPara("id");
		if (Common.isNotEmpty(id)) {
			model.addAttribute("datacenterJoinDbFromMap", new DatacenterFormMap().findById(id));
		}
		return Common.BACKGROUND_PATH + "/system/datacenter/edit";
	}

	// 修改活动
	@ResponseBody
	@RequestMapping("editFunc")
	@SystemLog(module = "系统管理", methods = "数据中心-修改用户密码") // 凡需要处理业务逻辑的.都需要记录操作日志
	@Transactional(readOnly = false) // 需要事务操作必须加入此注解
	public String editFunc(Model model) throws Exception {
		HashMap<String, Object> hashMap=getMapFromRequest();
		hashMap.remove("token");
		DatasourceFuncFormMap datasourceFuncFormMap=getMapformDataMap(DatasourceFuncFormMap.class, hashMap);
		try {
			datasourceFuncFormMap.put("df_updater", Common.findUserSessionAccountName());
			datasourceFuncFormMap.put("df_update_time", Common.addDateDay(0));
			if (datasourceFuncFormMap.get("func_parent_id").equals("20")) {
				datasourceFuncFormMap.put("func_status", 0);
			}
			
			datasourceFuncFormMap.update();
		}catch (DuplicateKeyException e) {
			e.printStackTrace();
			return "duplicate";
		} catch (Exception e) {
			
			e.printStackTrace();
			return "failed";
		}
		return "success";
	}

	// 修改活动
	@ResponseBody
	@RequestMapping("editEntity")
	@SystemLog(module = "系统管理", methods = "数据中心-修改用户密码") // 凡需要处理业务逻辑的.都需要记录操作日志
	@Transactional(readOnly = false) // 需要事务操作必须加入此注解
	public String editEntity(Model model) throws Exception {
		DatacenterFormMap datacenterJoinDb = getFormMap(DatacenterFormMap.class);
		if (Common.isNotEmpty(datacenterJoinDb.get("id").toString())) {
			datacenterJoinDb.update();
		}
		return "success";
	}
	/////////// ----------- 只管上面这个 这里就得到数据了 ----------///////////////

	// 验证方法
	@ResponseBody
	@RequestMapping("isExist")
	public boolean isExist(String name) {
		DatacenterFormMap datacenterJoinDb = getFormMap(DatacenterFormMap.class);
		List<DatacenterFormMap> list = datacenterJoinDb.findByNames();
		if (list.size() == 0) {
			return true;
		} else {
			return false;
		}
	}

	// 修改时的验证方法
	@ResponseBody
	@RequestMapping("editisExist")
	public boolean editisExist() {
		// TODO datacenterJoinDb，没有数据
		DatacenterFormMap datacenterJoinDb = getFormMap(DatacenterFormMap.class);
		// 先根据名称去找，没有就返回true
		// 有的话就判断是不是这id的记录，如果是的话也返回true
		// 否则返回false
		List<DatacenterFormMap> list = datacenterJoinDb.findByAttribute("id", datacenterJoinDb.get("id"));
		if (list.size() == 0) {
			return true;
		} else {
			if (list.size() >= 0) {
				List<DatacenterFormMap> list2 = datacenterJoinDb.findByNames();
				if (list2.size() > 0) {
					return true;
				} else {
					return false;
				}
			}
			return false;
		}
	}

}
